package cn.xxstudy.visitshop.ui.activity.main.fragment.train

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import cn.xxstudy.visitshop.R
import cn.xxstudy.visitshop.adapter.FooterAdapter
import cn.xxstudy.visitshop.adapter.HeaderAdapter
import cn.xxstudy.visitshop.adapter.TrainPagingDataAdapter
import cn.xxstudy.visitshop.base.fragment.LazyFragment
import cn.xxstudy.visitshop.ui.activity.main.fragment.train.viewmodel.TrainViewModel
import cn.xxstudy.visitshop.util.configAppearance
import kotlinx.android.synthetic.main.activity_visit_details.*
import kotlinx.android.synthetic.main.fragment_train.*
import kotlinx.android.synthetic.main.include_toolbar.*
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 * @author ：DELL on 2021/3/23 .
 * @packages cn.xxstudy.visitshop.ui.activity.main.fragment.train
 * @TODO: 培训
 */
class TrainFragment : LazyFragment(), SwipeRefreshLayout.OnRefreshListener {

    private val viewModel by lazy { ViewModelProvider(this).get(TrainViewModel::class.java) }
    private val adapter = TrainPagingDataAdapter()
    override val layoutId = R.layout.fragment_train

    override fun initView() {
        toolbarTitle.text = "培 训"
        trainContent.configAppearance(context)
        trainRefresh.configAppearance()
        trainRefresh.setOnRefreshListener(this)
    }


    override fun loadData() {
        trainContent.adapter = adapter.withLoadStateFooter(FooterAdapter { adapter.retry() })
        trainRefresh.post {
            trainRefresh.isRefreshing = true
            lifecycleScope.launch {
                viewModel.getPagingData().collect { pagingData ->
                    adapter.submitData(pagingData)
                }
            }
        }
        adapter.addLoadStateListener {
            when (it.refresh) {
                is LoadState.NotLoading -> {
                    trainRefresh.isRefreshing = false
                }
                is LoadState.Error -> {
                    trainRefresh.isRefreshing = false
                    val state = it.refresh as LoadState.Error
                    Toast.makeText(context, state.error.message, Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onRefresh() {
        viewModel.getPagingData()
        adapter.refresh()
    }

}